<?php
namespace app\ota\controller;
use app\common\BaseController;
use app\ota\model\Team as TeamModel;
use app\ota\model\Single as SingleModel;
use app\ota\model\TeamIncome as TeamIncomeModel;
use app\ota\model\TeamOutlay as TeamOutlayModel;

use think\Db;
class Unified extends BaseController{    
    public function __construct(){
        parent::__construct();      
    }
    public function index(){        
        $json = file_get_contents('php://input');                        
        $params = json_decode(stripslashes($json),true);
        //$params = $this->request->param();
        //var_dump($params);exit;
        //type,1：团队，4：单项
        //1：跟团游、一日游、游学、定制游、邮轮、自由行、机+酒、景+酒
         //4：签证、保险、门票、1.0旅游订单
       
        if(empty($params['type'])){
            return $this->callback(0,"缺少分类type");           
        }
        if(empty($params['shop'])){
            return $this->callback(0,"缺少门店名shop");        
         }
        if(empty($params['sn'])){
            return $this->callback(0,"缺少订单号sn");          
         }
         if(empty($params['product_name'])){
            return $this->callback(0,"缺少产品名称product_name");           
         }
         if(empty($params['booking_date'])){
            return $this->callback(0,"缺少订单日期booking_date");
         }
         if(empty($params['start_date'])){
            return $this->callback(0,"缺少出发日期start_date");           
         }         
                 
         if(empty($params['operatorName'])){
            return $this->callback(0,"缺少操作员operatorName");
         }
         
         
        //携程状态：待确认0，已确认1，已完成2，已取消4，全部退订3，已归档5
         //status状态：1已归档，2已取消，3全部退订，4已完成，5已确定

         //已取消订单
         /*
         if(in_array($params['status'],array(2,3))){
            if(in_array($params['type'],[1,2,3,4,5,6,7,8])){
               $teamModel = new TeamModel();      
               $teamIncomeModel = new TeamIncomeModel(); 
               $teamOutlayModel = new TeamOutlayModel(); 
               $team = $teamModel->where('sn',$params['sn'])->find();             
               if($team){
                  $teamModel  ->where('id',$team['id'])->delete(); 
                  $teamIncomeModel  ->whereIn('parent_id',$team['id'])->delete(); 
                  $teamOutlayModel  ->whereIn('parent_id',$team['id'])->delete(); 
                  return;
               }else{
                  return;
               }
            }else{
               $model = new SingleModel();     
               $isbeing = $model->where('sn',$params['sn'])->find();
               if($isbeing){                  
                  $num = $model  ->where('id',$isbeing['id'])->delete();                              
               }else{
                  return;
               }
            }
         }
         */
         //正常订单
         //if(empty($params['cost_price'])){
            //$this->callback(0,"缺少总金额cost_price");
            //return;
         //}
         //if(empty($params['num'])){
            //$this->callback(0,"缺少数量num");
            //return;
         //}
         if(empty($params['guests'])){
            //$this->callback(0,"缺少客人资料guests");
            //return;
            $params['guests']=[];
         }         
         if(in_array($params['status'],array(1,2,5))){
            if(in_array($params['type'],[1,2,3,4,5,6,7,8])){
               return $this->team($params);
            }else{
               return $this->single($params);
            }
         }else{
            return $this->callback(0,"不上报此状态订单");
         }
    }

    public function team($params){
      $teamModel = new TeamModel();  
      $isbeing = $teamModel->where('sn',$params['sn'])->find();        
      $operatorID = $this->operator($params);
      $team['operator_id'] = $operatorID;
      $team['branch_id'] = $this->branch($params['shop']);  
      $team['type'] = 1;
      $team['category_id'] = $this->category($params['type']);
      $team['title'] = $params['product_name'];
      $team['sn'] = $params['sn'];
      $team['num'] = $params['num'];
      $team['start_date'] = $params['start_date'];
      $team['end_date'] = !empty($params['end_date'])?$params['end_date']:'';
      if($isbeing){
         return $this->callback(0,"订单已存在");         
      }else{
         $team_data = $teamModel->allowField(true)->isUpdate(false)->data($team)->save();         
      }      
      if($team_data){ 
         foreach ($params['guests'] as $k=> $v) {
            //收入            
            $income_data['guest_id']="";
            $income_data['parent_id'] = $teamModel->id;
            $income_data['client_id'] = 126;
            $income_data['num'] = 1;
            $income_data['sell_price'] = $params['sales']['adult_price'];             
            $income_data['kind_id']=43;
            $income_data['salesman_id'] = $operatorID;
            $income_data['type'] = $team['type'];          
            $income_data['guest_id'] = $this->guest($v,$operatorID);
            $teamIncome_data = Db::name('team_income')->insert($income_data);               
         }
         //支出        
         $outlay_data['supplier_id'] = $params['supplier_id'] = $this->supplier($params,$operatorID);
         $outlay_data['product_name']=$params['product_name'];
         $outlay_data['kind_id']=43;
         $outlay_data['num']=$params['num'];
         $outlay_data['cost_price']=$params['cost_price']/$params['num'];
         $outlay_data['parent_id'] = $teamModel->id;
         $outlay_data['type'] = $team['type'];           
         $teamOutlay_data = Db::name('team_outlay')->insert($outlay_data);
      }
      return $this->callback(1,"成功");      
    }

    public function single($params){
      $model = new SingleModel();  
      $operatorID = $this->operator($params);  
      $params['category_id'] = $this->category($params['type']);
      $params['client_id'] = 126;     
      $params['supplier_id'] = $this->supplier($params,$operatorID);              
      $operatorID = $this->operator($params);
      $params['operator_id'] = $operatorID;
      $params['salesman_id'] = $operatorID;       
      $params['branch_id'] = $this->branch($params['shop']);  
      $params['guest_id'] = $this->guest($params['guests'][0],$operatorID);
      $params['cost_price'] = $params['cost_price']/$params['num'];      
      $params['sell_price'] = $params['sales']['adult_price'];    
      $params['type'] =4;
      $isbeing = $model->where('sn',$params['sn'])->find();
      if($isbeing){
         return $this->callback(0,"订单已存在");        
      }else{
         $data = $model->allowField(true)->isUpdate(false)->data($params)->save();
      }            
      return $this->callback(1,"成功");     
    }

    public function guest($params,$operator_id){
      $guest = Db::name('guest')->where("guest_name",$params['name'])->find();            
      if($guest){
         return $guest['id'];            
      }else{
         $phone=!empty($params['phone'])?$params['phone']:"";
         Db::name('guest')->insert([
            'guest_name'=>$params['name'],
            'phone'=>$phone,
            'sex'=>$params['sex'],
            'birthday'=>$params['birthday'],
            'country'=>$params['country'],
            'certificate_type'=>$params['certificate_type'],
            'certificate'=>$params['certificate_no'],
            'operator_id'=>$operator_id
            ]);
         $guestId = Db::name('guest')->getLastInsID();
         return $guestId;          
      }
    }

    public function operator($params){
      $operatorID = Db::name('manager')->where("cn_name",$params['operatorName'])->value('id');            
      if($operatorID){
         return $operatorID;        
      }else{
         Db::name('manager')->insert(['user_name'=>md5($params['operatorName']),'cn_name'=>$params['operatorName'],'role_id'=>2]);
         $operatorID = Db::name('manager')->getLastInsID();
         return $operatorID;        
      }
    }

    public function supplier($params,$operator_id){
      $supplierID = Db::name('supplier')->where("supplier_name",$params['shop'])->value('id');            
      if($supplierID){
         return $supplierID;
      }else{
         Db::name('supplier')->insert(['supplier_name'=>$params['shop'],'operator_id'=>$operator_id]);
         $supplierID = Db::name('supplier')->getLastInsID();
         return $supplierID;
      }
    }

    public function category($type){
      switch ($type)
      {
      case in_array($type,[1,2,3,4,5,6]):
        return 42;
        break;  
       case 7:
         return 97;
        break;
        case 8:
         return 98;
        break;
      case 9:
         return 69;
        break;
      case 10:
         return 95;
         break;
      case 11:
         return 67;
         break;
      case 12:
         return 62;
         break;      
      }
   }

   public function branch($params){
      switch ($params)
      {
      case "台西店：广州携程国际旅行社有限公司（TDS2）":
        return 33;
        break;  
      case "桔园店：广州携程国际旅行社有限公司（TDS2）":
         return 32;
        break;     
      }
   }
   
    public function callback($code,$msg){
        $message = ["code"=>$code,"msg"=>$msg];
        return $message;
    }
 }